package com.iamsleeping;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by Mohit on 05-Apr-14.
 */
public class CallDaemon extends BroadcastReceiver {
	
	int count=1;

    public void onReceive(Context context, Intent intent) {

        try {
            // TELEPHONY MANAGER class object to register one listner
            TelephonyManager telephonyManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            //Create Listner
            MyPhoneStateListener PhoneListener = new MyPhoneStateListener(context);
            // Register listener for LISTEN_CALL_STATE
            telephonyManager.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
        } catch (Exception e) {
            Log.e("Phone Receive Error", " " + e);
        }

    }

    private class MyPhoneStateListener extends PhoneStateListener {
        Context mContext;
        Settings settings;

        public MyPhoneStateListener(Context context) {
            mContext = context;
            settings = Settings.getInstance(context);
        }

        public void onCallStateChanged(int state, String incomingNumber) {
            Log.d("MyPhoneListener", state + "   incoming no:" + incomingNumber);
            if (settings.getAppStatus()) {
                if (state == TelephonyManager.CALL_STATE_RINGING) {
                    String msg = "New Phone Call Event. Incoming Number : " + incomingNumber;
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
                    toast.show();
                    if(count==1)
                    {
                    SmsManager sms = SmsManager.getDefault();
                    sms.sendTextMessage(incomingNumber, null, settings.getMsgText(), null, null);
                    count++;
                    }
                    else
                    {
                    	count++;
                    }

                }
            }
        }
    }
}